package com.example.quartzdemo.memory;

import com.example.quartzdemo.Entity.QuartzBean;
import com.example.quartzdemo.observer.JobChangerWatcher;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

/**
 * 内存缓存list实现，被观察者
 *
 * @author yeyangtao
 * @since 2022/6/20 14:36
 */
public class LocalCacheList extends Observable implements LocalCache {

    private static List<QuartzBean> data = new ArrayList<>();

    public static LocalCache localCache = new LocalCacheList();

    @Override
    public boolean add(QuartzBean target) {
        data.add(target);
        super.setChanged();
        super.notifyObservers();
        return true;
    }

    @Override
    public QuartzBean get(String id) {
        return data.stream().filter(d -> id.equals(d.getId())).findFirst().orElseGet(QuartzBean::new);
    }

    @Override
    public boolean del(String id) {
        data.removeIf(q -> id.equals(q.getId()));
        super.notifyObservers();
        return true;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public List<QuartzBean> getAll() {
        return data;
    }

    @Override
    public void observer() {
        this.addObserver(new JobChangerWatcher());
    }
}
